import { request } from '@/utils/request'
/**
 * post请求
 * @param {url} url
 * @param {参数} parameter
 */
export function postAction(url, parameter, type) {
	let req = {
		url: url,
		method: 'post',
		showMessage: true,
		data: parameter,
		type,
	}
	// if (timeout || timeout == 0) {
	// 	req.timeout = timeout
	// }
	return request(req)
}

/**
 * put请求
 * @param {url} url
 * @param {参数} parameter
 */
export function putAction(url, parameter) {
	let req = {
		url: url,
		method: 'put',
		showMessage: true,
		data: parameter,
	}
	// if (timeout || timeout == 0) {
	// 	req.timeout = timeout
	// }
	return request(req)
}

/**
 * get请求
 * @param {url} url
 * @param {参数} parameter
 * @param {超时时间，0表示永不超时} timeout
 */
export function getAction(url, parameter, timeout) {
	let req = {
		url: url,
		method: 'get',
		params: parameter,
	}
	if (timeout || timeout == 0) {
		req.timeout = timeout
	}
	return request(req)
}

/**
 * delete请求
 * @param {url} url
 * @param {参数} parameter
 * @param {超时时间，0表示永不超时} timeout
 */
export function deleteAction(url, parameter, timeout) {
	let req = {
		url: url,
		method: 'delete',
		params: parameter,
	}
	if (timeout || timeout == 0) {
		req.timeout = timeout
	}
	return request(req)
}

/**
 * 下载文件 用于excel导出
 * @param url
 * @param parameter
 * @returns {*}
 */
export function downFile(url, parameter) {
	return request({
		url: url,
		params: parameter,
		method: 'get',
		responseType: 'blob',
	})
}

/**
 * 下载文件 用于excel导出 post方式
 * 2022-05-27 人员综合查询列全选时,导出时用downFile【get】方法，参数超长 ,特此增加downFilePost【post】方法用来导出
 * @param url
 * @param parameter
 * @returns {*}
 */
export function downFilePost(url, parameter) {
	return request({
		url: url,
		data: parameter,
		method: 'post',
		responseType: 'blob',
	})
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */

export function resolveBlob(res, mimeType) {
	if (res) {
		const aLink = document.createElement('a')
		const blob = new Blob([res.data], { type: mimeType })
		// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
		const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
		const contentDisposition = decodeURI(res.headers['content-disposition'])
		const result = patt.exec(contentDisposition)
		let fileName = result[1]
		fileName = fileName.replace(/\"/g, '')
		aLink.href = URL.createObjectURL(blob)
		aLink.setAttribute('download', fileName) // 设置下载文件名称
		document.body.appendChild(aLink)
		aLink.click()
		document.body.appendChild(aLink)
	}
}

export function uploadFile(url, parameter, timeout) {
	let req = {
		url: url,
		data: parameter,
		method: 'post',
		responseType: 'blob',
		headers: {
			'Content-Type': 'multipart/form-data',
		},
	}
	if (timeout) {
		req.timeout = timeout
	}
	return request(req)
}
